<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.3, maximum-scale=1.0, user-scalable=0,shrink-to-fit=no, viewport-fit=cover">
    <meta name="keywords" content="蓝桥到家">
    <meta name="description" itemprop="description" content="生鲜副食、饮品乳品、鲜花蛋糕">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="../styles/reset.css" />
    <link rel="stylesheet" type="text/css" href="../styles/login.css">
    <link rel="stylesheet" type="text/css" href="../styles/common.css" />
    <script src="../js/common.js"></script>
    <script src="../js/zepto.min.js"></script>
    <style>
        /* 错误提示样式（统一验证码和密码登录的错误提示） */
        .error-tip {
            color: #ff4d4f; /* 统一红色错误提示 */
            font-size: 140px; /* 修正字体大小 */
            margin: -5px 0 18px 70px; /* 统一与输入框的间距 */
            display: none; /* 默认隐藏 */
            font-weight: 500; /* 统一字重 */
            line-height: 1.5; /* 统一行高 */
            height: 21px; /* 固定高度，避免切换登录方式时布局跳动 */
        }
        .code.disabled {
            background: #ccc;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="container">
            <!-- logo start-->
            <div class="header_logo">
                <img src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/lanqiao-logo.1bbdf85.svg" />
            </div>
            <!-- logo end -->

            <ul class="login_tab">
                <li class="cur"> <span>验证码登录</span> </li>
                <li> <span>密码登录</span> </li>
            </ul>
            <!-- 登录 start-->
            <ul class="login_show">
                <li class="cur">
                    <div class="login_item">
                        <span class="login_text">手机号</span>
                        <input class="login_input" type="tel" maxlength="11" value="18712341234" placeholder="输入手机号" id="codePhone"/>
                    </div>
                    <p class="error-tip" id="codePhoneError">请输入正确的手机号</p>
                    
                    <div class="login_item">
                        <span class="login_text">验证码</span>
                        <div class="auth_div">
                            <input class="login_input" type="text" maxlength="4" value="1234" placeholder="输入验证码" id="verifyCode"/>
                            <div class="code" id="getCodeBtn">
                                <span>获取验证码</span>
                            </div>
                        </div>
                    </div>
                    <p class="error-tip" id="codeError">验证码错误</p>
                    
                    <div class="login_button">
                        <a href="javascript:;" id="codeLoginBtn"><span>登录</span></a>
                    </div>
                </li>
                <li>
                    <div class="login_item">
                        <span class="login_text">手机号</span>
                        <input class="login_input" type="tel" maxlength="11" placeholder="输入手机号" id="pwdPhone"/>
                    </div>
                    <p class="error-tip" id="pwdPhoneError">请输入正确的手机号</p>
                    
                    <div class="login_item">
                        <span class="login_text">密码</span>
                        <input class="login_input" type="password" maxlength="12" placeholder="输入密码" id="loginPwd"/>
                    </div>
                    <p class="error-tip" id="pwdError">密码错误</p>
                    
                    <div class="login_button">
                        <a href="javascript:;" id="pwdLoginBtn"><span>登录</span></a>
                    </div>
                </li>
            </ul>
            <!-- 登录 end-->
            <div class="register_div">
                <a class="register_text" href="register.html">注册账号</a>
            </div>
        </div>
    </div>
    <script>
        // 从data.json获取用户数据（修正路径为上一级目录）
        async function getUsers() {
            try {
                console.log('开始请求用户数据...');
                const response = await fetch('../data.json'); // 上一级目录
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                const data = await response.json();
                console.log('用户数据获取成功:', data);
                return data.users || [];
            } catch (error) {
                console.error('获取用户数据失败:', error);
                alert('系统错误，请稍后重试');
                return [];
            }
        }

        // 验证手机号格式
        function isPhoneValid(phone) {
            const reg = /^1[3-9]\d{9}$/;
            return reg.test(phone);
        }

        // 切换登录类型时隐藏所有错误提示
        $('.login_tab li').click(function() {
            if ($(this).hasClass('cur')) return;
            $(this).addClass('cur').siblings().removeClass('cur');
            const index = $(this).index();
            $(".login_show li").eq(index).addClass('cur').siblings().removeClass('cur');
            $('.error-tip').hide();
        });

        // 验证码登录-获取验证码
        $('#getCodeBtn').click(async function() {
            const phone = $('#codePhone').val().trim();
            if (!isPhoneValid(phone)) {
                $('#codePhoneError').show();
                return;
            }
            $('#codePhoneError').hide();

            // 从data.json检查用户是否存在
            const users = await getUsers();
            const userExists = users.some(u => u.phone === phone);
            if (!userExists) {
                if (confirm('该手机号未注册，是否前往注册？')) {
                    window.location.href = `register.html?phone=${phone}`;
                }
                return;
            }

            // 模拟倒计时
            const $btn = $(this).addClass('disabled');
            let count = 60;
            const timer = setInterval(() => {
                $btn.find('span').text(`${count}s后重新获取`);
                count--;
                if (count < 0) {
                    clearInterval(timer);
                    $btn.removeClass('disabled').find('span').text('获取验证码');
                }
            }, 1000);

            // 自动填充验证码
            $('#verifyCode').val('1234');
        });

        // 验证码登录-登录按钮
        $('#codeLoginBtn').click(async function() {
            const phone = $('#codePhone').val().trim();
            const code = $('#verifyCode').val().trim();
            let isValid = true;

            // 验证手机号
            if (!isPhoneValid(phone)) {
                $('#codePhoneError').show();
                isValid = false;
            } else {
                $('#codePhoneError').hide();
            }

            // 验证验证码
            if (code !== '1234') {
                $('#codeError').show();
                isValid = false;
            } else {
                $('#codeError').hide();
            }

            // 验证通过且用户存在则登录
            if (isValid) {
                const users = await getUsers();
                const userExists = users.some(u => u.phone === phone);
                if (!userExists) {
                    alert('该手机号未注册');
                    return;
                }
                alert('登录成功');
                window.location.href = '../index.html';
            }
        });

        // 密码登录-登录按钮（修复无响应问题）
        $('#pwdLoginBtn').click(async function() {
            console.log('密码登录按钮被点击'); // 调试日志
            const phone = $('#pwdPhone').val().trim();
            const pwd = $('#loginPwd').val().trim();
            let isValid = true;

            // 验证手机号
            if (!isPhoneValid(phone)) {
                $('#pwdPhoneError').show();
                isValid = false;
            } else {
                $('#pwdPhoneError').hide();
            }

            // 验证密码
            if (pwd === '') {
                $('#pwdError').text('请输入密码').show();
                isValid = false;
            } else {
                // 从data.json检查用户和密码
                try {
                    const users = await getUsers();
                    const user = users.find(u => u.phone === phone);
                    if (!user || user.password !== pwd) {
                        $('#pwdError').text('手机号或密码错误').show();
                        isValid = false;
                    } else {
                        $('#pwdError').hide();
                    }
                } catch (error) {
                    console.error('密码验证出错:', error);
                    alert('登录失败，请重试');
                    isValid = false;
                }
            }

            // 验证通过则登录
            if (isValid) {
                alert('登录成功');
                window.location.href = '../index.html';
            }
        });

        // 输入时隐藏对应错误提示
        $('.login_input').on('input', function() {
            $(this).closest('.login_item').next('.error-tip').hide();
        });

        // 切换到密码登录时，自动隐藏错误提示
        $('.login_tab li:eq(1)').click(function() {
            $('#pwdPhoneError').hide();
            $('#pwdError').hide();
        });
    </script>
</body>
</html>